const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MyPromise {
    constructor(executor) {
        try {
            executor(this.resolve, this.reject);
        } catch (error) {
            this.reject(error)
        }
    }

    //  promise状态值
    status = PENDING;
    //  成功之后的值
    value = undefined;
    //  失败之后的值
    reason = undefined;
    //  成功之后的回调函数
    successCallback = [];
    //  失败之后的回调函数
    failCallback = [];

    resolve = (value) =>  {
        //  如果状态不是等待状态，则阻止程序向下执行
        if (this.status !== PENDING) return;
        //  更改状态为成功
        this.status = FULFILLED;
        this.value = value;
        //  处理异步情况是，有成功回调则调用函数
        while(this.successCallback.length)  this.successCallback.shift()()
    }

    reject = (reason) => {
        //  如果状态不是等待状态，则阻止程序向下执行
        if (this.status !== PENDING) return;
        //  更改状态为失败
        this.status = REJECTED;
        this.reason = reason;
        //  处理异步情况是，有失败回调则调用函数
        while(this.failCallback.length)  this.failCallback.shift()()
    }

    then (successCallback, failCallback) {
        //  处理当then不传递参数时，等价于讲value继续像下传递，直到传递到有回调的函数中去
        successCallback = successCallback ? successCallback : value => value;
        failCallback = failCallback ? failCallback: reason => { throw reason};
        //  实现promise的链式调用，则必须返回一个promise
        const promise2 = new MyPromise((resolve, reject) => {
            if(this.status === FULFILLED) {
                //  setTimeout是为了拿到pormise2
                setTimeout(() => {
                    try {
                        const x = successCallback(this.value);
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        const x = failCallback(this.reason);
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            } else if (this.status === PENDING) {
                //  当为异步时，先把回调存储起来，当resolve或者reject时调用
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            const x = successCallback(this.value);
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                });
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            const x = failCallback(this.reason);
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                });
            }
        })
        return promise2;
    }

    catch(callback) {
        return this.then(undefined, callback)
    }

    finally(callback) {
        //  返回这个then是为了链式调用
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value);
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason });
        })
    }

    static all(array) {
        const result = [];
        let i = 0;
        return new MyPromise((resolve, reject) => {
            const addData = (key, value) => {
                result[key] = value;
                i++;
                if (i === array.length) {
                    resolve(result);
                }
            }
            array.forEach((item, index) => {
                if (item instanceof MyPromise) {
                    item.then(x => addData(index, x), reason => reject(reason))
                } else {
                    addData(index, item)
                }
            });
        })
    }

    static resolve(value) {
        if (value instanceof MyPromise) {
            return value;
        } else {
            return new MyPromise(resolve => resolve(value))
        }

    }
}

//  判断x的值是普通值还是promise对象
//  如果是普通值则直接调用resolve
//  如果是rpomise对象,查看promise对象返回结果
//  再根据promise对象返回结果，决定调用resolve还是reject
function resolvePromise(promise2, x, resolve, reject) {
    if (promise2 === x) {
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        x.then(resolve, reject);
    } else {
        resolve(x)
    }
}


// const promise = new MyPromise((resolve, reject) => {
//     setTimeout(() => {
//         resolve('成功')
//     }, 2000)
//     reject('失败')
// })

// const promise1 = new MyPromise((resolve, reject) => {
//     // setTimeout(() => {
//     //     resolve('成功')
//     // }, 2000)
//     setTimeout(() => {
//         resolve('成功2')
//     }, 2000)
// })

// promise.then(() => {
//     console.log(1);
//     return 
// })

/*-------------------------------------------------------------------------------------------------------- */

//  自己返回自己报错

const promise3 = new MyPromise((resolve, reject) => {
    resolve('成功')
})

const p1 = promise3.then(value => {
    console.log(value)
    return p1;
})
p1.then(value => {
    console.log(value);
}, (reason) => {
    console.log(reason)
})

/*-------------------------------------------------------------------------------------------------------- */

//  执行器错误，会在then中的reject返回

const promise4 = new MyPromise((resolve, reject) => {
    throw new Error('executor error');
})

promise4.then(value => {
    console.log(value)
}, err => {
    console.log(err)
})

//  then中状态为成功的时候执行错误，会在下一个then中的reject中返回

const promise5 = new MyPromise((resolve, reject) => {
    resolve('成功')
})

promise5.then(value => {
    console.log(value)
    throw new Error('then error')
}, error => {
    console.log(error)
}).then(value => {
    console.log(value)
}, error => {
    console.log(error)
})

//  then中状态为失败的时候执行错误，会在then中的reject中返回

const promise6 = new MyPromise((resolve, reject) => {
    reject('失败')
})

promise6.then(value => {
    console.log(value)
}, error => {
    console.log(error)
    return 100
}).then(value => {
    console.log(value)
}, error => {
    console.log(error)
})

// 当为异步时，执行回调错误处理

const promise7 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('成功');
        // reject('失败')
    }, 2000)
})

promise7.then(value => {
    console.log(value)
    return 'aaa'
}, error => {
    console.log(error)
    return 100
}).then(value => {
    console.log(value)
}, error => {
    console.log(error)
})

/*-------------------------------------------------------------------------------------------------------- */


//  then中的参数不传递

const promise8 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('then中的参数不传递 成功');
        // reject('失败')
    }, 2000)
})

promise8
.then()
.then(value => {
    console.log(value)
    throw new Error('回调出错向下传递')
}, error => {
    console.log(error)
})
.then()
.then(value => {
    console.log(value)
}, error => {
    console.log('接收到错误信息' + error)
})

/*-------------------------------------------------------------------------------------------------------- */

//  promise.all

const promise9 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('proimise all方法调用');
        // reject('失败')
    }, 2000)
})

MyPromise.all([1, 2, promise9, 3]).then(result => {
    console.log(result);
})

/*-------------------------------------------------------------------------------------------------------- */

//  promise.resolve
MyPromise.resolve(2).then(value => console.log('静态resolve方法' + value));

/*-------------------------------------------------------------------------------------------------------- */

//  promise.finally
const promise10 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('proimise finally方法调用');
        // reject('失败')
    }, 2000)
})

promise10.finally(() => {
    console.log('finally执行了');
}).then(value => {
    console.log(value);
}, error => {
    console.log(error);
})

/*-------------------------------------------------------------------------------------------------------- */

//  promise.catch
const promise11 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        reject('proimise catch方法调用');
        // reject('失败')
    }, 2000)
})

promise11.catch(error => console.log(error))

/*-------------------------------------------------------------------------------------------------------- */


